package bean;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import util.Encrypt;
import dao.JPA;
import dao.RoleDAO;
import dao.UserDAO;
import entity.Role;
import entity.User;

@ManagedBean
@ViewScoped
public class EditUserBean {

	@Inject @JPA
	private UserDAO userDAO;
	@Inject @JPA
	private RoleDAO roleDAO;
	@Inject
	private ActiveSessionsStoreBean usersBean;		
	private User user = new User();
	private List<Role> roleList;	
	private boolean editMode;	
	private String initialPass;
	
	@PostConstruct
	private void init() {		
		roleList = roleDAO.findAll();
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		if(params.get("userId") != null) {
			int userId = Integer.valueOf(params.get("userId"));
			user = userDAO.getEntityById(userId);
			if(user == null)
				redirectToPageNotFound();
			initialPass = user.getPass();
			editMode = true;			
		}
	}
	
	public void invalidateUserSession() {
		usersBean.invalidateSession(user.getName());
	}
	
	public void editUser() {	
		if(editMode) {
			if(!user.getPass().equals(initialPass))
				user.setPass(Encrypt.encryptSHA256(user.getPass()));
			userDAO.merge(user);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "User updated", "User updated"));
		} 
		else { 
			user.setPass(Encrypt.encryptSHA256(user.getPass()));
			userDAO.persist(user);
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "User created", "User created"));
			goBack();
		}				
	}
	
	public void deleteUser() {
		usersBean.invalidateSession(user.getName());
		userDAO.remove(user);
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "User deleted", "User deleted"));
		goBack();
	}
	
	public List<Role> getRoleList() {
		return roleList;
	}
	
	public User getUser() {
		return user;
	}

	public boolean isEditMode() {
		return editMode;
	}
	
	public void goBack() {
		try {
			if(editMode)
				FacesContext.getCurrentInstance().getExternalContext().redirect("../admin/viewUserList.xhtml");
			else FacesContext.getCurrentInstance().getExternalContext().redirect("../loggedIn/menu.xhtml");
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	private void redirectToPageNotFound() {
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("../error/404.xhtml");
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}

}
